package com.itnetwork.ServiceImp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.itnetwork.DaoImp.NewsDaoImp;
import com.itnetwork.Entity.Category;
import com.itnetwork.Entity.News;
import com.itnetwork.commons.XmlToHtml;

@Component("newServiceImp")
public class NewServiceImp {
		//spring注入
	/*	static void prin()
		{
			System.out.print("Ok");
		}*/
		private HibernateTemplate hibernateTemplate;
		private String  xslPath;
		private StreamSource xslSource,xmlSource;
		private Logger logger=(Logger) LoggerFactory.getLogger(NewServiceImp.class);
		private NewsDaoImp newsDaoImp;
		@Transactional(readOnly=true)
		public int getCount(int cid)
		{
			int totalPeoperty;
			totalPeoperty=newsDaoImp.getCount(cid);
			return totalPeoperty; 
		}
		//分页获取新闻
		@Transactional(readOnly=true)
		public List<News> getNewsList(int start,int limit,int cid)
		{
			
			List<News> newslist = new ArrayList<News>();
			newslist = newsDaoImp.getNewsList(start, limit,cid);
			
			return newslist;
			
		}
		//存储单条新闻
		@Transactional
		public  void saveNews(News news)
		{
			newsDaoImp.saveNews(news);
		}
/*******************************************************************************************/
		
		
/*******************************************************************************************/
		public void writeToHtml(String xslPath,String path,News news) throws TransformerException, IllegalArgumentException, IOException, IllegalAccessException, InvocationTargetException
		{
			//xslPath=="c:/sdf/sdf/../news/category/news.xsl"
			//path=="c:/sdf/sdf/../news/category/date.toString"
			System.out.println("Path="+path);
			System.out.println("xmlBasePath="+xslPath);
			File htmlFile;
			this.xslPath=xslPath;   //暂时这样保存xsl所在文件目录
			String xmlPath=path+".xml";
			String htmlPath=path+".html";
			
			System.out.println("xmlPath="+xmlPath);
			System.out.println("xmlPath="+htmlPath);
			if(xslPath!=null){
				System.out.println(xslPath);
				xslSource=new StreamSource(xslPath);
				if(xslSource!=null)
				{
					System.out.println("already");
				}else{
					System.out.println("no ready");
				}
				};
			xmlSource=new StreamSource(this.writeToXml(news, xmlPath));
			
			htmlFile=new File(htmlPath);
			XmlToHtml.write(xslSource, xmlSource, htmlFile);
		}
		
		public String  writeToXml(News news,String xmlPath) throws IllegalArgumentException, FileNotFoundException, IOException, IllegalAccessException, InvocationTargetException
		{
			//xmlPath=="c:/sdf/../s/df.xml"
			String categoryTitle=news.getCategory().getCtitle();
			//String categoryPath=contextPath+"\\"+categoryTitle+"\\";
			if(categoryTitle!=null)
			{
				System.out.println("栏目路径："+categoryTitle);
				if(xmlPath!=null)
				{
					//targetFileName=categoryPath+targetFileName;
					Format xmlDocumentFormat = Format.getPrettyFormat();
					xmlDocumentFormat.setIndent("   ");
					xmlDocumentFormat.setEncoding("utf-8");
					XMLOutputter xmlDocumentOuter=new XMLOutputter(xmlDocumentFormat);
					xmlDocumentOuter.output(this.builXMLdocument(news), new FileOutputStream(xmlPath));
					System.out.println("完成生成xml文件，路径为："+xmlPath);
				}else{
					System.out.println("文件名为空");
				}
			}else{
				System.out.println("栏目路径不存在");
			}
			logger.info("生成xml文件");
			return xmlPath;
		}
		
		public Document builXMLdocument(News news) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
		{
			if(news!=null)
			{
				System.out.println("news not null");
			}
			Element documentRoot,firstLevelTag;
			Document xmlDocument = new Document();
			
			documentRoot =new Element("news");
			xmlDocument.addContent(documentRoot);
			Class nwsClass=news.getClass();
			Method[] methods=nwsClass.getMethods();
			System.out.println(methods.length);
			for(Method m:methods)
			{
				String tag=m.getName();
			if(tag.indexOf("get")!=-1&&!tag.equalsIgnoreCase("getClass")){///
					//System.out.println(tag.lastIndexOf("get"));
					tag=tag.substring(tag.lastIndexOf("get")+3);
					System.out.println(tag);
				firstLevelTag=new Element(tag);
				Object o=m.invoke(news,null);
				if(o!=null){
					if(o instanceof Category)
					{
						firstLevelTag.setText(((Category)o).getCtitle());
					}else{
						System.out.println(o.toString());
						firstLevelTag.setText(o.toString());
					}
					documentRoot.addContent(firstLevelTag);
				}else{
					System.out.println("m invoke tag null="+tag);
				}
																		}////
				
			}
			logger.info("构建xmldocument任务完成");
			return xmlDocument;
			
		}
		//插入一条新闻
		public void insertNew(News news)
		{
			hibernateTemplate.save(news);
		}

		public NewsDaoImp getNewsDaoImp() {
			return newsDaoImp;
		}
		@Resource(name="newsDaoImp")
		public void setNewsDaoImp(NewsDaoImp newsDaoImp) {
			this.newsDaoImp = newsDaoImp;
		}
/*******************************************************************************************/
	public List<News> dealwithNewsO(List<News> newslist)
	{
		//List<News> newslist
		Category category;
		for(News n:newslist)
		{
			category = n.getCategory();
			n.setCid(category.getCid());//为了传送给前台此新闻对应的栏目（在news实体对象里面加了@Transient cid，ctitle属性），其实也未必要用到，
			n.setCtitle(category.getCtitle());
			//n.setCategory(null);//暂时对查询出来的new对象回环内嵌对象造成转换json报错的解决方法
		}
		return newslist;	//回传一个处理后的List对象
	}
}
